package com.liuzh.kaoyanspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuzh.kaoyanspringboot.common.Constants;
import com.liuzh.kaoyanspringboot.common.Result;
import com.liuzh.kaoyanspringboot.entity.Dict;
import com.liuzh.kaoyanspringboot.entity.Menu;
import com.liuzh.kaoyanspringboot.service.DictService;
import com.liuzh.kaoyanspringboot.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-02
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private DictService dictService;

    // 新增或更新
    @PostMapping
    public Result save(@RequestBody Menu menu) {
        return Result.success(menuService.saveOrUpdate(menu));
    }

    // 根据 id 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {

        return Result.success(menuService.deleteById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(menuService.removeBatchByIds(ids));
    }

    //查询所有数据
    @GetMapping
    public Result findAll(@RequestParam(defaultValue = "") String name) {
        if(!"".equals(name)){
            QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name",name);
            // 若需要 查询菜单名字则不区分 一级菜单或二级菜单直接返回
            return Result.success(menuService.list(queryWrapper));
        }
        // 否则根据一二级菜单查出所有数据
        return Result.success(menuService.findMenus());
    }

    // 根据 id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(menuService.getById(id));
    }

    //简单的分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");
        return Result.success(menuService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @GetMapping("/icons")
    public Result getIcons() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constants.DICT_TYPE_ICON);
        return Result.success(dictService.list(queryWrapper));
    }

}

